package com.fansl.allround.study.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fansl
 * @Description: TODO
 * @date 2019/12/12 18:15
 */
@Slf4j
@RestController
public class SmsSendThread {
    @Autowired
    private SmsService smsService;
    @Autowired
    private AliSmsSendHandler aliSmsSendHandler;

    @GetMapping
    public  void send() {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new ThreadFactory() {
            /**
             *原子操作保证每个线程都有唯一的
             */
            private final AtomicInteger threadNumber=new AtomicInteger(1);

            private final AtomicInteger mThreadNum = new AtomicInteger(1);


            @Override
            public Thread newThread(Runnable runnable) {
                String name = "study-" + mThreadNum.getAndIncrement();
                Thread ret = new Thread( runnable, name);
                threadNumber.getAndIncrement();
                if(ret.isDaemon()){
                    ret.setDaemon(false);
                }
                ;
                return ret;
            }
        });
         for (int i=0;i<100;i++){
             int finalI = i;
             CompletableFuture.runAsync(()->{
                 try{
                     String uuid = UUID.randomUUID().toString();
                     smsService.setServiceName("serviceName"+finalI);
                     SmsConfig smsConfig = new SmsConfig();
                     smsConfig.setConfigName("configName"+finalI);

                     log.info("{},set sms config,{}",uuid,smsConfig);
                     aliSmsSendHandler.setSmsConfig(smsConfig);
                     log.info("{},set sms service,{}",uuid,smsService);
                     aliSmsSendHandler.setSmsService(smsService);
                     aliSmsSendHandler.send(uuid,"消息:"+ finalI);
                 }catch (Exception e){
                     e.printStackTrace();
                 }
             },poolExecutor);
         }
    }
}
